import { http } from '@/utils/http';
import { useUserStore } from '@/stores/useUserStore';
import { filterBaseUrl } from "@/utils/common";

// App更新参数
interface AppUploadParams {
	title ?: string,
	content ?: string,
	canceltext ?: string,
	oktext ?: string,
	showTip ?: boolean,
}

function check(param : AppUploadParams = {}) {
	// 合并默认参数
	param = Object.assign({
		title: "检测到有新版本！",
		content: "请升级app到最新版本！",
		canceltext: "暂不升级",
		oktext: "立即升级"
	}, param)
	const url = '/system/sysappversion/latestAppDownloadUrl'
	plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
		let platform = plus.os.name.toLocaleLowerCase()
		http({
			method: 'POST',
			url: url,
			data: {}
		}).then((result : any) => {
			let data = result.data ? result.data : null;
			if (widgetInfo.version >= data.versionName) {
				param?.showTip && uni.showToast({
					icon: 'success',
					title: '当前为最新版本'
				})
				return;
			}
			if (result.code == 200) {
				if (platform == 'ios') {
					// 如果是ios,则跳转到appstore
					plus.runtime.openURL(data.appUrl)
					return;
				}
				uni.showModal({
					title: param.title,
					content: param.content,
					showCancel: data.forceUpdate === '1' ? false : true,
					confirmText: param.oktext,
					cancelText: param.canceltext,
					success: async (res) => {
						if (!res.confirm) {
							plus.runtime.quit();
						}
						if (data.shichang === 1) {
							//去应用市场更新
							plus.runtime.openURL(data.shichangurl);
							plus.runtime.restart();
						} else {
							// 清除缓存
							useUserStore().token && await useUserStore().logout();

							// 开始下载
							// 创建下载任务
							const dtask = plus.downloader.createDownload(filterBaseUrl(url) + '/system/fileCenter/preview/' + data.appUrl, {
								filename: "_downloads/",
							},
								function (d, status) {
									// 下载完成
									if (status == 200) {
										plus.runtime.install(d.filename, {
											force: true
										}, function () {
											//进行重新启动;
											plus.runtime.restart();
										}, (e) => {
											uni.showToast({
												title: '安装升级包失败:' + JSON
													.stringify(e),
												icon: 'none'
											})
										});
									} else {
										uni.showToast({
											title: "下载升级包失败，请手动去站点下载安装，错误码: " + status,
											icon: "none"
										})
									}
								});

							try {
								dtask.start(); // 开启下载的任务
								let prg = 0;
								const showLoading = plus.nativeUI.showWaiting('正在下载'); //创建一个showWaiting对象
								dtask.addEventListener("statechanged", (e) => {
									// 给下载任务设置一个监听 并根据状态  做操作
									switch (e.state) {
										case 1:
											showLoading.setTitle('正在下载');
											break;
										case 2:
											showLoading.setTitle('已连接到服务器');
											break;
										case 3:
											prg = Number(((e.downloadedSize / data.totalSize) * 100).toFixed(0));
											showLoading.setTitle('  正在下载 ' + prg + '%  ');
											break;
										case 4:
											plus.nativeUI.closeWaiting(); //下载完成
											break;
									}
								}, false);
							} catch (e) {
								plus.nativeUI.closeWaiting();
								uni.showToast({
									title: 'App更新失败',
									mask: false,
									duration: 1500
								});
							}

						}
					}
				})
			}
		})
	});
}

export default {
	check
}